﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Windows;
using JHoelsch.DataClases.Serialization;

namespace JHoelsch.DataClases.DataBase
{
    abstract public class SerializableObject : DependencyObject
    {
        public SerializableObject()
        {
            Id = Guid.NewGuid();
            HasChanges = false;
        }
        public static readonly DependencyProperty isVisibilyProperty = DependencyProperty.Register("showSave", typeof(Visibility), typeof(SerializableObject));
        [System.Xml.Serialization.XmlIgnoreAttribute()]
        public Visibility visibilty
        {
            get
            {
                return (Visibility)GetValue(isVisibilyProperty);
            }
            set
            {
                SetValue(isVisibilyProperty, value);
            }
        }
        private bool hasChanges = false; 
        [System.Xml.Serialization.XmlIgnoreAttribute()]
        public bool HasChanges {
            get
            {
                return hasChanges;
            }
            set
            {
                if (value == true) visibilty = Visibility.Visible;
                else visibilty = Visibility.Hidden;
                hasChanges = value;
            }
        }
        [System.Xml.Serialization.XmlIgnoreAttribute()]
        private string m_filename;
        [System.Xml.Serialization.XmlIgnoreAttribute()]
        public string FilenameWithPath
        {
            get
            {
                return this.m_filename;
            }
            set
            {
                if (!value.Equals(m_filename, StringComparison.CurrentCultureIgnoreCase))
                {
                    HasChanges = true;
                    m_filename = value;
                }
            }
        }
        public Guid Id { get; set; }
        public void save()
        {
            JHoelsch.DataClases.Serialization.XmlSerializationTool.writeToFile(this, FilenameWithPath);
            HasChanges = false;
        }
        public static T load<T>(string filename) where T : SerializableObject, new()
        {
            T loaded = (T)XmlSerializationTool.readFromFile<T>(filename);
            if (loaded != null) loaded.FilenameWithPath = filename;
            loaded.HasChanges = false;
            return loaded;
        }
    }
}
